package server.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;

import java.util.List;

/**
 * CheckWin
 *
 * @author
 * @date 2024-06-08 17:12
 */
public class CheckWin {
    public static boolean checkWin(List<JSONArray> jsonArrayList, int x, int y) {
        if (jsonArrayList.size() < 5) {
            return false;
        }

        // 检查水平方向
        int horizontalCount = 0;
        for (JSONArray piece : jsonArrayList) {
            try {
                int pieceX = piece.getInteger(0);
                int pieceY = piece.getInteger(1);
                if (pieceX == x && Math.abs(pieceY - y) < 5) {
                    horizontalCount++;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (horizontalCount >= 5) {
            return true;
        }

        // 检查垂直方向
        int verticalCount = 0;
        for (JSONArray piece : jsonArrayList) {
            try {
                int pieceX = piece.getInteger(0);
                int pieceY = piece.getInteger(1);
                if (pieceY == y && Math.abs(pieceX - x) < 5) {
                    verticalCount++;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (verticalCount >= 5) {
            return true;
        }

        // 检查主对角线方向（右上到左下）
        int mainDiagonalCount = 0;
        for (JSONArray piece : jsonArrayList) {
            try {
                int pieceX = piece.getInteger(0);
                int pieceY = piece.getInteger(1);
                if (Math.abs(pieceX - x) == Math.abs(pieceY - y) && Math.abs(pieceX - x) < 5) {
                    mainDiagonalCount++;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (mainDiagonalCount >= 5) {
            return true;
        }

        // 检查副对角线方向（左上到右下）
        int subDiagonalCount = 0;
        for (JSONArray piece : jsonArrayList) {
            try {
                int pieceX = piece.getInteger(0);
                int pieceY = piece.getInteger(1);
                if (Math.abs(pieceX - x) == Math.abs(pieceY - y) && Math.abs(pieceX - x) < 5) {
                    subDiagonalCount++;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (subDiagonalCount >= 5) {
            return true;
        }

        return false;
    }
}
